package com.zh.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zh.entity.Goods;
import com.zh.entity.Lunar;
import com.zh.service.GoodsService;
import com.zh.service.LunarService;
import com.zh.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/5/4/004.
 */
@RestController
@RequestMapping("lunar")
public class LunarController extends BaseController {
    public static String LUNAR_URL = "https://www.sojson.com/open/api/lunar/json.shtml";//?date=2018-05-04

    @Autowired
    LunarService lunarService;

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/get")
    public Result getList(@NotNull(message = "时间不能为空")String time){
        System.out.println("-------------------------------------------------------------------");
        return Result.success(lunarService.selectList(new EntityWrapper<Lunar>()));
    }

    @RequestMapping("/set")
    public Result setList(@NotNull(message = "时间不能为空") String time){
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = LUNAR_URL;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        //得到的json数据
        System.out.println(result);
        //解析,
        JSONObject jsonObj = JSON.parseObject(result);

        //输出该ip对应的地理位置
        System.out.println("------------------------------------------");
        System.out.println(jsonObj.toString());
        return Result.success();
    }
}
